﻿using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using DG.Tweening;
public class AutoNumber : MonoBehaviour {

	private Text autoText;
	private int nowValue;
    private int minValue;
    private int maxValue;
    private int leftValue;

    private bool hasMaxValue;
    private bool hasMinValue;

	// Use this for initialization
	void Awake () {
		autoText = gameObject.GetComponent<Text> ();
		leftValue = 0;
		nowValue = 0;
        StartCoroutine (RunAddNum());
	}

    public void Reset() {
        nowValue = minValue;
        leftValue = 0;
        autoText.text = nowValue + "";

    }

    //设置最大值，一旦设置，就会标记hasMaxValue，这个数字就会最多显示到maxValue
    public int MaxValue {
        get {
            return maxValue;
        }
        set {
            maxValue = value;
            hasMaxValue = true;
        }
    }

    public int MinValue
    {
        get
        {
            return minValue;
        }
        set
        {
            minValue = value;
            hasMinValue = true;
        }
    }

    public bool HasMaxValue {
        get {
            return hasMaxValue;
        }
    }

    public bool HasMinValue {
        get {
            return hasMinValue;
        }
    }

    public void SetInitText(int initValue)
    {
        nowValue = initValue;
        autoText.text = initValue.ToString();
    }


	public void AddNum(int addValue){
		leftValue += addValue;
    }

    public void Jump() {
        DOTween.Kill("NumberJump");
        transform.localScale = Vector3.one;
        Sequence seq = DOTween.Sequence();
        seq.Append(transform.DOScale(1.3f, 0.2f));
        seq.Append(transform.DOScale(1f, 0.2f));
        seq.SetId("NumberJump");
        seq.Play();
    }

	private IEnumerator RunAddNum(){
		while (true) {
			if(Mathf.Abs(leftValue) > 0){
				int offset = leftValue > 0 ? 1 : -1;
                if (Mathf.Abs(leftValue) / 1000000 > 0)
                    offset *= 100000;
                else if (Mathf.Abs(leftValue) / 100000 > 0)
                    offset *= 10000;
                else if (Mathf.Abs(leftValue) / 10000 > 0)
					offset *= 1000;
				else if(Mathf.Abs(leftValue) / 1000 > 0)
					offset *= 100;
				else if(Mathf.Abs(leftValue) / 100 > 0)
					offset *= 10;
				nowValue += offset;
				leftValue -= offset;

                if (hasMaxValue && nowValue > maxValue) {
                    nowValue = maxValue;
                }

                if (hasMinValue && nowValue < minValue)
                {
                    nowValue = minValue;
                }

                autoText.text = nowValue + "";
			}
			yield return null;
		}
	}

}
